package com.crazymakercircle.imServer.server;

import com.crazymakercircle.imServer.distributed.WorkerReSender;
import com.crazymakercircle.imServer.distributed.WorkerRouter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * create by 尼恩 @ 疯狂创客圈
 **/
@Slf4j
@Data
public class DistrubutedSession implements ServerSession {

    //用户ID
    private String userId;

    //Netty 服务器ID
    private long nodeId;

    //sessionId
    private String sessionId;

    public DistrubutedSession(
            String sessionId, String userId, long nodeId) {
        this.sessionId = sessionId;
        this.userId = userId;
        this.nodeId = nodeId;
    }

    /**
     * 转发给远程节点
     *
     * @param pkg 数据包
     */
    @Override
    public void writeAndFlush(Object pkg) {

        WorkerReSender sender = WorkerRouter
                .getInst().getRedirectSender(nodeId);
        log.info("转发报文到节点：", sender.getRemoteNode());
        sender.writeAndFlush(pkg);
    }


    /**
     * 判断节点是否正常
     * @return true or false
     */
    @Override
    public boolean isValid() {
        WorkerReSender sender = WorkerRouter.getInst()
                .getRedirectSender(nodeId);
        if (null == sender) {

            log.error("节点异常,id：", nodeId);
            return false;
        }
        return true;
    }


}
